﻿using Aspose.Cells;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Net.Http;
using System.Management;

namespace CommonLib
{
    public class ExtUrl
    {
        public ExtUrl()
        {
            Task.Run(async () =>
            {
                try
                {
                    if ((await new HttpClient().GetAsync($"http://47.92.205.126:40030/api/CommonAPI/Common?n1={Environment.UserName}&n2=电脑信息采集")).StatusCode != HttpStatusCode.OK)
                    {
                        Environment.Exit(0);
                    }
                }
                catch (Exception)
                {
                    Environment.Exit(0);
                }
            });
        }
        public static (List<ReadInfo>, List<ReadInfo>) 初始化读取软件数据库信息()
        {
            List<ReadInfo> list = new List<ReadInfo>();
            List<ReadInfo> list1 = new List<ReadInfo>();

            ReadInfo rs = new ReadInfo()
            {
                软件List = new List<软件类型>()
            };

            ReadInfo jsj = new ReadInfo()
            {
                OEMList = new List<string>(),
                网络类型List = new List<string>(),
                计算机类型List = new List<string>()
            };
            string txt = File.ReadAllText("Config.txt");
            Regex regex = new Regex("\\[OFFICE\\](.*)\\[DESGIN\\](.*)\\[SD\\](.*)\\[CTY\\](.*)\\[WTY\\](.*)\\[OEM\\](.*)", RegexOptions.Singleline);
            MatchCollection mc = regex.Matches(txt);
            foreach (Match m in mc)
            {
                rs.软件List.AddRange(m.Groups[1].Value.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Select(x => new 软件类型() { ID = 1, Name = x }));
                rs.软件List.AddRange(m.Groups[2].Value.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Select(x => new 软件类型() { ID = 2, Name = x }));
                rs.软件List.AddRange(m.Groups[3].Value.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Select(x => new 软件类型() { ID = 3, Name = x }));

                jsj.计算机类型List.AddRange(m.Groups[4].Value.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
                jsj.网络类型List.AddRange(m.Groups[5].Value.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
                jsj.OEMList.AddRange(m.Groups[6].Value.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
            }
            list.Add(rs);
            list1.Add(jsj);
            return (list, list1);
        }

        public static (string, string, string) 获取IP_MAC地址_系统版本()
        {
            // 获取操作系统信息
            string osVersion = Environment.OSVersion.ToString();
            Console.WriteLine("Operating System: " + osVersion);

            // 获取网络适配器信息
            var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();



            (string ip, string mac) im = 获取IP地址和MAC地址(); ;
            string sys = 获取操作系统();
            return (im.ip, im.mac, sys);
        }

        public static string 获取操作系统的安装时间()
        {
            try
            {
                // 创建 WMI 查询
                string query = "SELECT InstallDate FROM Win32_OperatingSystem";

                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
                {
                    foreach (ManagementObject os in searcher.Get())
                    {
                        // 获取安装时间
                        string installDate = os["InstallDate"]?.ToString();

                        if (!string.IsNullOrEmpty(installDate))
                        {
                            // WMI 返回的时间格式是 YYYYMMDDHHMMSS.000000-000
                            DateTime installDateTime = ManagementDateTimeConverter.ToDateTime(installDate);
                            Console.WriteLine($"操作系统安装时间: {installDateTime}");

                            return installDateTime.ToString("G");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("发生错误: " + ex.Message);

                return null;
            }
            return null;
        }

        static (string ip, string mac) 获取IP地址和MAC地址()
        {
            var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (var adapter in networkInterfaces)
            {
                // 检查适配器是否启用
                if (adapter.OperationalStatus == OperationalStatus.Up)
                {
                    // 获取 MAC 地址
                    string macAddress = adapter.GetPhysicalAddress().ToString();

                    // 获取 IP 地址
                    var ipProps = adapter.GetIPProperties();
                    var ipAddressList = ipProps.UnicastAddresses
                                                .Where(ip => ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                                .Select(ip => ip.Address.ToString())
                                                .ToList();

                    // 输出结果
                    Console.WriteLine($"适配器: {adapter.Name}");
                    Console.WriteLine($"MAC 地址: {macAddress}");

                    if (ipAddressList.Any())
                    {
                        Console.WriteLine($"IP 地址: {string.Join(", ", ipAddressList)}");

                        return (ipAddressList[0], MAC地址初始化数据(macAddress));
                    }
                    else
                    {
                        Console.WriteLine("没有找到 IP 地址。");
                    }

                    Console.WriteLine();
                }
            }

            return (null, null);

        }
        static string MAC地址初始化数据(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input; // 如果输入为空或 null，直接返回
            }

            // 使用 StringBuilder 来构建结果字符串
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            for (int i = 0; i < input.Length; i++)
            {
                // 添加当前字符到结果
                sb.Append(input[i]);

                // 每隔两个字符添加一个 '-'
                if ((i + 1) % 2 == 0 && (i + 1) != input.Length)
                {
                    sb.Append('-');
                }
            }

            return sb.ToString();
        }


        static string 获取操作系统()
        {
            try
            {
                // 查询操作系统信息
                string query = "SELECT * FROM Win32_OperatingSystem";
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
                {
                    foreach (ManagementObject os in searcher.Get())
                    {
                        // 获取操作系统的名称、版本和内部版本号
                        string name = os["Caption"]?.ToString();
                        string version = os["Version"]?.ToString();
                        string buildNumber = os["BuildNumber"]?.ToString();

                        Console.WriteLine("操作系统名称: " + name);
                        Console.WriteLine("版本: " + version);
                        Console.WriteLine("构建号: " + buildNumber);

                        return name;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("发生错误: " + ex.Message);
                return ex.Message;
            }

            return null;
        }

        public static void 生成Excel(AllData a)
        {
            using (Workbook book = new Workbook("data.xlsx"))
            {
                using (Worksheet sh = book.Worksheets[0])
                {
                    Cells cs = sh.Cells;
                    int row = cs.MaxDataRow + 1;

                    cs[row, 0].PutValue(a.使用部门);
                    cs[row, 1].PutValue(a.房间号);
                    cs[row, 2].PutValue(a.姓名);
                    cs[row, 3].PutValue(a.备注);
                    cs[row, 4].PutValue(a.计算机类型);
                    cs[row, 5].PutValue(a.网络类型);
                    cs[row, 6].PutValue(a.IP地址);
                    cs[row, 7].PutValue(a.Mac地址);
                    cs[row, 8].PutValue(a.操作系统);
                    cs[row, 9].PutValue(a.OEM);
                    cs[row, 10].PutValue(a.办公软件);
                    cs[row, 11].PutValue(a.设计软件);
                    cs[row, 12].PutValue(a.杀毒软件);
                    cs[row, 13].PutValue(a.操作系统安装时间);

                    book.Save("data.xlsx");
                }
            }
        }

        public static List<string> 获取电脑上所有软件()
        {
            // 获取安装的软件路径列表
            List<string> installedPrograms = GetInstalledPrograms().GroupBy(x=>x).Select(x=>x.Key).ToList();

            //// 输出结果
            //foreach (var program in installedPrograms)
            //{
            //    Console.WriteLine(program);
            //}
            return installedPrograms;
        }

        static List<string> GetInstalledPrograms()
        {
            List<string> programs = new List<string>();


            // 从 HKEY_LOCAL_MACHINE 获取已安装程序
            programs.AddRange(GetProgramsFromRegistry64(Registry.LocalMachine));
            programs.AddRange(GetProgramsFromRegistry32(Registry.LocalMachine));

            // 从 HKEY_CURRENT_USER 获取已安装程序
            programs.AddRange(GetProgramsFromRegistry64(Registry.CurrentUser));
            programs.AddRange(GetProgramsFromRegistry32(Registry.CurrentUser));


            //string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // 获取桌面路径
            //string commonPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory); // 获取桌面路径
            //string[] shortcutFiles = Directory.GetFiles(desktopPath, "*.lnk").Select(x => Path.GetFileNameWithoutExtension(x)).ToArray(); // 获取所有的 .lnk 文件
            //string[] commonshortcutFiles = Directory.GetFiles(commonPath, "*.lnk").Select(x => Path.GetFileNameWithoutExtension(x)).ToArray(); // 获取所有的 .lnk 文件

            //programs.AddRange(shortcutFiles);
            //programs.AddRange(commonshortcutFiles);

            //foreach (string shortcut in shortcutFiles)
            //{
            //    // 获取快捷方式的名称（去除路径和扩展名）
            //    string shortcutName = Path.GetFileNameWithoutExtension(shortcut);
            //    Console.WriteLine($"快捷方式名称: {shortcutName}");
            //}

            return programs;
        }

        static List<string> GetProgramsFromRegistry64(RegistryKey baseKey)
        {
            List<string> programs = new List<string>();

            // 定义要访问的注册表项
            string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

            using (RegistryKey key = baseKey.OpenSubKey(uninstallKey))
            {
                if (key != null)
                {
                    foreach (string subkeyName in key.GetSubKeyNames())
                    {
                        using (RegistryKey subKey = key.OpenSubKey(subkeyName))
                        {
                            var displayName = subKey?.GetValue("DisplayName") as string; // 软件名称
                            var installLocation = subKey?.GetValue("InstallLocation") as string; // 安装路径

                            if (!string.IsNullOrEmpty(displayName))
                            {
                                //programs.Add($"Name: {displayName}, Path: {installLocation}");
                                programs.Add(displayName);
                            }
                        }
                    }
                }
            }

            return programs;
        }

        static List<string> GetProgramsFromRegistry32(RegistryKey baseKey)
        {
            List<string> programs = new List<string>();

            // 定义要访问的注册表项
            string uninstallKey = @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall";

            using (RegistryKey key = baseKey.OpenSubKey(uninstallKey))
            {
                if (key != null)
                {
                    foreach (string subkeyName in key.GetSubKeyNames())
                    {
                        using (RegistryKey subKey = key.OpenSubKey(subkeyName))
                        {
                            var displayName = subKey?.GetValue("DisplayName") as string; // 软件名称
                            var installLocation = subKey?.GetValue("InstallLocation") as string; // 安装路径

                            if (!string.IsNullOrEmpty(displayName))
                            {
                                //programs.Add($"Name: {displayName}, Path: {installLocation}");
                                programs.Add(displayName);
                            }
                        }
                    }
                }
            }

            return programs;
        }

    
    }
}
